package com.neusoft.elmboot.filter;

import com.fasterxml.jackson.databind.ObjectMapper;

import com.neusoft.elmboot.common.Result;
import com.neusoft.elmboot.po.User;
import com.neusoft.elmboot.utils.JWTUtil;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JwtLoginFilter extends AbstractAuthenticationProcessingFilter {

    /**
     * 忽略权限认证的 URL数组
     */
    public static final String [] IGNORE_AUTHORIZE_URLS = {"/user/info"};

    public JwtLoginFilter(String defaultFilterProcessesUrl, AuthenticationManager authenticationManager) {
        super(new AntPathRequestMatcher(defaultFilterProcessesUrl));
        setAuthenticationManager(authenticationManager);
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest req, HttpServletResponse resp)
            throws AuthenticationException, IOException, ServletException {
        System.out.println("----------1.JwtLoginFilter.attemptAuthentication():");
        User user = new ObjectMapper().readValue(req.getInputStream(), User.class);
        return getAuthenticationManager().authenticate(new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword()));
    }

    @Override
    protected void successfulAuthentication(HttpServletRequest req, HttpServletResponse resp, FilterChain chain,
                                            Authentication authResult) throws IOException, ServletException {
        System.out.println("----------2.JwtLoginFilter.successfulAuthentication():");
        Collection<? extends GrantedAuthority> authorities = authResult.getAuthorities();
        StringBuffer as = new StringBuffer();
        for (GrantedAuthority authority : authorities) {
            as.append(authority.getAuthority())
                    .append(",");
        }

       /* String jwt = Jwts.builder()
                .claim("authorities", as)//配置用户角色 
                .setSubject(authResult.getName())
                .setExpiration(new Date(System.currentTimeMillis() + 10 * 60 * 1000))
                .signWith(SignatureAlgorithm.HS512, "sang@123")
                .compact();*/
        System.out.println("----------authResult:"+authResult);

        User u = null;
        if(null != authResult && authResult.getPrincipal() instanceof  User) {
            u = (User)authResult.getPrincipal();
        }

        String authStr = "";
        if (as.length()>0) {
            authStr = as.substring(0,as.length()-1);
        }
        String jwt = JWTUtil.generateToken(u.getUserId(),authStr);

        resp.setContentType("application/json;charset=utf-8");
        PrintWriter out = resp.getWriter();

        Map<String,Object> retMap = new HashMap<>();
        retMap.put("user",u);
        retMap.put("token", jwt);
        Result x = Result.success(retMap, "登录成功！");

        out.write(new ObjectMapper().writeValueAsString(x));
        out.flush();
        out.close();
    }

    protected void unsuccessfulAuthentication(HttpServletRequest req, HttpServletResponse resp,
                                              AuthenticationException failed) throws IOException, ServletException {
        System.out.println("----------3.JwtLoginFilter.unsuccessfulAuthentication():");
        resp.setContentType("application/json;charset=utf-8");
        PrintWriter out = resp.getWriter();

        Result x = Result.fail(500, "登录失败，请检查用户名和密码！");

        out.write(new ObjectMapper().writeValueAsString(x));
        out.flush();
        out.close();
    }
} 